﻿using Guest_room.BLL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Windows.Forms;

namespace Guest_room.admin
{
    public partial class employee : Form
    {
        public employee()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }
        //几个数据表几个适配器   三个
        SqlDataAdapter daEmployee, daLog;
        DataSet ds = new DataSet();//适配器对象
        string num = null;//编号
        GuestRoomService guestRoomService = new GuestRoomService();
        void init()
        {
            DB.GetCn();
            string str = "select * from 员工基本信息表";
            string slr = "select * from 日志表";
            daEmployee = new SqlDataAdapter(str, DB.cn);
            daLog = new SqlDataAdapter(slr, DB.cn);
            daEmployee.Fill(ds, "employee_info");
            daLog.Fill(ds, "log_info");
            num = guestRoomService.GetNum();
            DB.cn.Close();
        }
        void showAll()//显示全部
        {
            DataView dvEployee = new DataView(ds.Tables["employee_info"]);
            dataGridView1.DataSource = dvEployee;
            //字体居中
            dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //列名居中
            dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //列宽自适应列名
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
        }
        void showXz()//显示选择列
        {
            DataGridViewCheckBoxColumn acCode = new DataGridViewCheckBoxColumn();
            acCode.Name = "acCode";
            acCode.HeaderText = "选择";
            //显示在第一列
            dataGridView1.Columns.Insert(0, acCode);
            //宽度为40
            dataGridView1.Columns[0].Width = 40;
        }
        private void employee_Load(object sender, EventArgs e)//窗体加载函数
        {
            // TODO: 这行代码将数据加载到表“guest_roomDataSet4.部门基本信息表”中。您可以根据需要移动或移除它。
            this.部门基本信息表TableAdapter.Fill(this.guest_roomDataSet4.部门基本信息表);
            lbluser.Text = Home.username ?? Login.username;
            init();
            showAll();
            showXz();
        }

        private void label6_Click(object sender, EventArgs e)
        {

        }

        private void label7_Click(object sender, EventArgs e)
        {

        }
        private void btnadd_Click(object sender, EventArgs e)//添加
        {
            //判断必填项
            if (text_id.Text == "" || text_name.Text == "" || text_phone.Text == "")
            {
                MessageBox.Show("带*号为必填项");
            }
            else
            {
                if ((DateTime.Today.Year - dateTimePicker1.Value.Year) < 18)
                {
                    MessageBox.Show("员工年龄不能小于18岁");
                }
                else
                {
                    DB.GetCn();
                    string str = "select * from 员工基本信息表 where 员工编号='" + text_id.Text + "'";
                    DataTable dt = DB.GetDataSet(str);

                    if (dt.Rows.Count > 0)
                    {
                        MessageBox.Show("员工已存在");
                    }
                    else
                    {
                        DataRow drEm = ds.Tables["employee_info"].NewRow();
                        drEm["员工编号"] = text_id.Text;
                        drEm["员工姓名"] = text_name.Text;
                        drEm["员工性别"] = combo_sex.Text;
                        drEm["出生日期"] = dateTimePicker1.Value;
                        drEm["员工电话"] = text_phone.Text;
                        drEm["员工部门"] = combo_department.Text;
                        drEm["地址"] = text_address.Text;
                        drEm["入职时间"] = dateTimePicker2.Value;
                        drEm["简介"] = text_introduction.Text;
                        // drEm["工资"] = int.Parse(text_wages.Text);  //int.Parse()将字符串转换为整数
                        //工资若为空则为0，不为空则转换为整数
                        drEm["工资"] = text_wages.Text == "" ? 0 : int.Parse(text_wages.Text);
                        ds.Tables["employee_info"].Rows.Add(drEm);
                        DataRow drLog = ds.Tables["log_info"].NewRow();
                        drLog["操作员"] = lbluser.Text;
                        drLog["操作员编号"] = Home.userid ?? Login.userid;//判断是哪个方式登录
                        drLog["操作时间"] = DateTime.Now;
                        drLog["操作类型"] = "添加";
                        drLog["操作表"] = "员工基本信息表";
                        drLog["操作内容"] = "添加了员工编号为‘" + text_id.Text + "’的员工";
                        ds.Tables["log_info"].Rows.Add(drLog);
                        reset();
                        //跳转至所添加行
                        dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1];
                    }
                }
            }

        }
        private void button2_Click(object sender, EventArgs e)//填充测试数据
        {
            string id = "E0" + num;
            text_id.Text = id;
            text_name.Text = "郭" + num;
            text_address.Text = "江苏省南京市";
            text_introduction.Text = "我是大大怪";
            text_phone.Text = "1" + num + "45678901";
            text_wages.Text = num + "000";
            combo_department.Text = "采购部";
            combo_sex.Text = "男";
            dateTimePicker1.Value = new DateTime(2000, 1, 1, 12, 12, 12);
            //编号转化整数型加1
            num = (int.Parse(num) + 1).ToString("00");

        }
        private void btnReset_Click(object sender, EventArgs e)//重置
        {
            reset();
        }
        void reset()//重置
        {
            text_id.Text = "";
            text_name.Text = "";
            text_address.Text = "";
            text_introduction.Text = "";
            text_phone.Text = "";
            text_wages.Text = "";
            combo_department.Text = "";
            combo_sex.Text = "";
            dateTimePicker1.Value = DateTime.Now;
            dateTimePicker2.Value = DateTime.Now;
            checkBox1.Checked = false;
            checkBox2.Checked = false;
        }

        private void btnReback_Click(object sender, EventArgs e)//撤销按钮
        {
            ds.RejectChanges();
            showAll();
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)//多选变单选
        {
            if (checkBox1.Checked == false)
            {
                if (dataGridView1.Rows.Count > 0)   //判断是否有数据
                {
                    for (int i = 0; i < dataGridView1.Rows.Count; i++)  //遍历所有行
                    {
                        DataGridViewCheckBoxCell ck = dataGridView1.Rows[i].Cells["acCode"] as DataGridViewCheckBoxCell;    //获取当前行的选择框
                        ck.Value = (i != e.RowIndex) ? false : true;
                    }
                }
            }
        }
        private void button1_Click(object sender, EventArgs e)//删除
        {
            bool flag = false;
            string staff_id = "";
            if (dataGridView1.Rows.Count > 0)   //判断是否有数据
            {
                if (checkBox1.Checked == false) //判断是否是多选删除
                {
                    for (int i = 0; i < dataGridView1.Rows.Count; i++)
                    {
                        DataGridViewCheckBoxCell ck = dataGridView1.Rows[i].Cells["acCode"] as DataGridViewCheckBoxCell;
                        if (ck.Value != null && (bool)ck.Value)
                        {
                            if (MessageBox.Show("确定要删除吗？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                flag = true;
                                staff_id = dataGridView1.Rows[i].Cells["员工编号"].Value.ToString();
                                dataGridView1.Rows.Remove(dataGridView1.Rows[i]);
                                i--;
                            }
                            else
                            {
                                return;
                            }
                        }
                    }
                    if (flag)
                    {
                        MessageBox.Show("删除成功");
                        if (DB.GetDataSet("select * from 员工基本信息表 where 员工编号='" + staff_id + "'").Rows.Count > 0)//判断受否存在数据库中
                        {
                            DataRow drLog = ds.Tables["log_info"].NewRow();
                            drLog["操作员"] = lbluser.Text;
                            drLog["操作员编号"] = Home.userid ?? Login.userid;//判断是哪个方式登录
                            drLog["操作时间"] = DateTime.Now;
                            drLog["操作类型"] = "删除";
                            drLog["操作表"] = "员工基本信息表";
                            drLog["操作内容"] = "删除了员工编号为‘" + staff_id + "’的员工";
                            ds.Tables["log_info"].Rows.Add(drLog);
                        }
                        else
                        {
                            //尝试删除添加该数据时产生的日志
                            for (int i = 0; i < ds.Tables["log_info"].Rows.Count; i++)
                            {
                                if (ds.Tables["log_info"].Rows[i]["操作内容"].ToString().Contains(staff_id))    //Contains包含
                                {
                                    ds.Tables["log_info"].Rows[i].Delete();
                                    i--;
                                }
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("请选择要删除的行");
                    }
                }
                else    //多选删除
                {
                    //获取所有选中行
                    List<DataGridViewRow> list = new List<DataGridViewRow>();
                    //删除所有选中行
                    for (int i = 0; i < dataGridView1.Rows.Count; i++)
                    {
                        DataGridViewCheckBoxCell ck = dataGridView1.Rows[i].Cells["acCode"] as DataGridViewCheckBoxCell;
                        if (ck.Value != null && (bool)ck.Value)
                        {
                            list.Add(dataGridView1.Rows[i]);
                        }
                    }
                    if (list.Count > 0)
                    {
                        if (MessageBox.Show("确定要删除吗？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            for (int i = 0; i < list.Count; i++)
                            {
                                staff_id = list[i].Cells["员工编号"].Value.ToString();
                                dataGridView1.Rows.Remove(list[i]);
                                //判断删除的数据是否存在数据库中，若存在则添加删除日志，若不存在则不添加
                                if (DB.GetDataSet("select * from 员工基本信息表 where 员工编号='" + staff_id + "'").Rows.Count > 0)
                                {
                                    DataRow drLog = ds.Tables["log_info"].NewRow();
                                    drLog["操作员"] = lbluser.Text;
                                    drLog["操作员编号"] = Home.userid ?? Login.userid;//判断是哪个方式登录
                                    drLog["操作时间"] = DateTime.Now;
                                    drLog["操作类型"] = "删除";
                                    drLog["操作表"] = "员工基本信息表";
                                    drLog["操作内容"] = "删除了员工编号为" + staff_id + "的员工";
                                    ds.Tables["log_info"].Rows.Add(drLog);
                                }
                                else
                                {
                                    //尝试删除添加该数据时产生的添加日志
                                    for (int j = 0; j < ds.Tables["log_info"].Rows.Count; j++)
                                    {
                                        if (ds.Tables["log_info"].Rows[j]["操作内容"].ToString().Contains(staff_id))    //Contains包含
                                        {
                                            ds.Tables["log_info"].Rows[j].Delete();
                                            j--;
                                        }
                                    }
                                }
                            }
                            MessageBox.Show("删除成功");
                        }
                    }
                    else
                    {
                        MessageBox.Show("请选择要删除的行");
                    }

                }

            }
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)//修改（checkBox开关）
        {

            if (checkBox1.Checked == true)
            {
                MessageBox.Show("请先回到单选模式");
                checkBox2.CheckedChanged -= checkBox2_CheckedChanged;
                checkBox2.Checked = false;
                checkBox2.CheckedChanged += checkBox2_CheckedChanged;
                return;
            }
            else
            {
                bool flag = false;
                if (checkBox2.Checked == true)
                {
                    for (int i = 0; i < dataGridView1.Rows.Count; i++)
                    {
                        DataGridViewCheckBoxCell ck = dataGridView1.Rows[i].Cells["acCode"] as DataGridViewCheckBoxCell;
                        if (ck.Value != null && (bool)ck.Value)
                        {
                            flag = true;
                        }
                    }
                    if (flag)
                    {
                        //隐藏按钮
                        btnadd.Visible = false;
                        btnsave.Visible = false;
                        btnReback.Visible = false;
                        btnReset.Visible = false;
                        checkBox1.Visible = false;
                        int index = dataGridView1.CurrentRow.Index;
                        text_id.Text = dataGridView1.Rows[index].Cells["员工编号"].Value.ToString();
                        //不允许修改员工编号
                        text_id.ReadOnly = true;
                        text_name.Text = dataGridView1.Rows[index].Cells["员工姓名"].Value.ToString();
                        text_address.Text = dataGridView1.Rows[index].Cells["地址"].Value.ToString();
                        text_introduction.Text = dataGridView1.Rows[index].Cells["简介"].Value.ToString();
                        text_phone.Text = dataGridView1.Rows[index].Cells["员工电话"].Value.ToString();
                        text_wages.Text = dataGridView1.Rows[index].Cells["工资"].Value.ToString();
                        combo_department.Text = dataGridView1.Rows[index].Cells["员工部门"].Value.ToString();
                        combo_sex.Text = dataGridView1.Rows[index].Cells["员工性别"].Value.ToString();
                        dateTimePicker1.Value = Convert.ToDateTime(dataGridView1.Rows[index].Cells["出生日期"].Value.ToString());
                        dateTimePicker2.Value = Convert.ToDateTime(dataGridView1.Rows[index].Cells["入职时间"].Value.ToString());
                        groupBox1.Text = "修改员工信息";
                        //groupBox1背景颜色修改#ADD8E6
                        groupBox1.BackColor = Color.FromArgb(173, 216, 230);
                    }
                    else
                    {
                        MessageBox.Show("请选中表格中的一行");
                        //恢复checkbox状态
                        checkBox2.CheckedChanged -= checkBox2_CheckedChanged;
                        checkBox2.Checked = false;
                        checkBox2.CheckedChanged += checkBox2_CheckedChanged;
                        return;
                    }

                }
                else
                {
                    //显示按钮
                    btnadd.Visible = true;
                    btnsave.Visible = true;
                    btnReback.Visible = true;
                    btnReset.Visible = true;
                    checkBox1.Visible = true;
                    //将文本框内容更新到dataGridView1
                    int index = dataGridView1.CurrentRow.Index;
                    dataGridView1.Rows[index].Cells["员工编号"].Value = text_id.Text;
                    //不允许修改员工编号
                    text_id.ReadOnly = false;
                    dataGridView1.Rows[index].Cells["员工姓名"].Value = text_name.Text;
                    dataGridView1.Rows[index].Cells["地址"].Value = text_address.Text;
                    dataGridView1.Rows[index].Cells["简介"].Value = text_introduction.Text;
                    dataGridView1.Rows[index].Cells["员工电话"].Value = text_phone.Text;
                    dataGridView1.Rows[index].Cells["工资"].Value = text_wages.Text;
                    dataGridView1.Rows[index].Cells["员工部门"].Value = combo_department.Text;
                    dataGridView1.Rows[index].Cells["员工性别"].Value = combo_sex.Text;
                    dataGridView1.Rows[index].Cells["出生日期"].Value = dateTimePicker1.Value;
                    dataGridView1.Rows[index].Cells["入职时间"].Value = dateTimePicker2.Value;
                    groupBox1.Text = "添加员工信息,带*为必填项";
                    //groupBox1背景颜色修改为透明
                    groupBox1.BackColor = Color.Transparent;

                    //在数据集中强调修改的列
                    for (int i = 0; i < ds.Tables["employee_info"].Rows.Count; i++)
                    {
                        if (ds.Tables["employee_info"].Rows[i]["员工编号"].ToString() == text_id.Text)
                        {
                            for (int j = 0; j < ds.Tables["employee_info"].Columns.Count; j++)
                            {
                                try//若修改的数据不存在数据库中，则不强调
                                {
                                    if (ds.Tables["employee_info"].Rows[i][j, DataRowVersion.Original].ToString() != ds.Tables["employee_info"].Rows[i][j, DataRowVersion.Current].ToString())
                                    {
                                        dataGridView1.Rows[index].Cells[j + 1].Style.BackColor = Color.Yellow;
                                    }
                                    //若修改的数据与数据库中的数据相同，则不强调
                                    else
                                    {
                                        dataGridView1.Rows[index].Cells[j + 1].Style.BackColor = Color.White;
                                    }
                                }
                                catch
                                {
                                    continue;
                                }

                            }
                        }
                    }



                    //添加修改日志（若修改了多个字段，则将多个日志信息存储在数据库的一个条目中），若修改的数据不存在数据库中，则不添加
                    for (int i = 0; i < ds.Tables["employee_info"].Rows.Count; i++)   //遍历所有行
                    {
                        string modifyContent = ""; // 存储所有修改的值
                        for (int j = 0; j < ds.Tables["employee_info"].Columns.Count; j++)  //遍历所有列
                        {
                            try
                            {
                                if (ds.Tables["employee_info"].Rows[i][j, DataRowVersion.Original].ToString() != ds.Tables["employee_info"].Rows[i][j, DataRowVersion.Current].ToString())  //判断是否修改
                                {
                                    if (modifyContent != "")
                                    {
                                        modifyContent += "; "; // 用分号分隔多个修改值
                                    }
                                    modifyContent += "【" + ds.Tables["employee_info"].Columns[j].ColumnName + "】由{ " + ds.Tables["employee_info"].Rows[i][j, DataRowVersion.Original].ToString() + " }---->{ " + ds.Tables["employee_info"].Rows[i][j, DataRowVersion.Current].ToString() + " }";
                                }
                            }
                            catch
                            {
                                //跳出循环
                                MessageBox.Show("修改的数据不存在数据库中");
                                break;
                            }
                        }
                        if (modifyContent != "")
                        {
                            DataRow drLog = ds.Tables["log_info"].NewRow();
                            drLog["操作员"] = lbluser.Text;
                            drLog["操作员编号"] = Home.userid ?? Login.userid;//判断是哪个方式登录
                            drLog["操作时间"] = DateTime.Now;
                            drLog["操作类型"] = "修改";
                            drLog["操作表"] = "员工基本信息表";
                            drLog["操作内容"] = "修改了员工编号为‘" + ds.Tables["employee_info"].Rows[i]["员工编号"].ToString() + "’的员工，" + modifyContent;
                            ds.Tables["log_info"].Rows.Add(drLog);

                        }
                    }
                    reset();
                }
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)//多选清除
        {

            if (checkBox1.Checked == false)
            {
                //清除dataGridView1的选中行
                dataGridView1.ClearSelection();
                //清除dataGridView1的勾选行
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    dataGridView1.Rows[i].Cells[0].Value = false;
                }
            }
        }

        private void btnsave_Click(object sender, EventArgs e)//保存
        {
            try
            {
                SqlCommandBuilder cb = new SqlCommandBuilder(daEmployee);//自动生成SQL语句
                SqlCommandBuilder cl = new SqlCommandBuilder(daLog);    //自动生成SQL语句
                daEmployee.Update(ds, "employee_info"); //更新数据库
                daLog.Update(ds, "log_info");   //更新数据库
                MessageBox.Show("保存成功");
                reset();
                DB.cn.Close();
            }
            catch (SqlException ex)     //返回异常信息
            {
                MessageBox.Show(ex.Message);
            }
            showAll();
        }
    }
}

